package com.miniserver.tql.database.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.miniserver.tql.database.Configuration;
import com.miniserver.util.DKeyDesEncrypt;

public class ConfigurationImpl implements Configuration {
	/** 网站的根目录 */
	protected String webRoot;
	protected String fileName;
	/** 数据库连接参数 */
	protected HashMap<String, String> parameters = new HashMap<String, String>();

	public ConfigurationImpl(String webRoot, String fileName) throws Exception {
		this.webRoot = webRoot;
		this.fileName = fileName;
		this.init();
	}

	public ConfigurationImpl(String fileName) throws Exception {
		this.fileName = fileName;
		this.webRoot = "";
		this.init();
	}

	@Override
	public String getParamValue(String paramName) {
		if (this.parameters.containsKey(paramName)) {
			return this.parameters.get(paramName);
		} else {
			return "";
		}
	}

	@Override
	public String getWebRoot() {
		return this.webRoot;
	}

	private void init() throws Exception {
		File sourceFile;
		InputStream input = null;
		if (this.webRoot.equals("")) {
			sourceFile = new File(this.fileName);
			input = new FileInputStream(sourceFile);
		} else {
			sourceFile = new File(this.webRoot + this.fileName);
			input = new ByteArrayInputStream(DKeyDesEncrypt.decryptFileToBytes(sourceFile));
		}
		 
		try {
			XPath xpath = XPathFactory.newInstance().newXPath();
			NodeList nodes = (NodeList) xpath.evaluate("/params/add", new InputSource(input), XPathConstants.NODESET);
			for (int i = 0; i < nodes.getLength(); i++) {
				Node tNode = nodes.item(i);
				//
				Attr tName = (Attr) tNode.getAttributes().getNamedItem("name");
				if (tName == null) {
					throw new Exception("Invalid data config.");
				}
				//
				Attr tValue = (Attr) tNode.getAttributes().getNamedItem("value");
				if (tValue == null) {
					throw new Exception("Invalid data config.");
				}
				//
				this.parameters.put(tName.getValue(), tValue.getValue());
			}
		} catch (Exception ex) {
			throw ex;
		} finally {
			if (input != null)
				input.close();
		}
	}

}
